// ==UserScript==
// @name          TLBW - Restore Power Rank
// @description   Restores the power rank section to Team Liquid's sidebar
// @version       20120102
// @include       http://teamliquid.net/*
// @include       http://www.teamliquid.net/*
// @exclude       http://teamliquid.net/sc2/*
// @exclude       http://teamliquid.net/store/*
// @exclude       http://teamliquid.net/tlfe/*
// @exclude       http://teamliquid.net/tournaments/*
// @exclude       http://teamliquid.net/vods/*
// @exclude       http://www.teamliquid.net/sc2/*
// @exclude       http://www.teamliquid.net/store/*
// @exclude       http://www.teamliquid.net/tlfe/*
// @exclude       http://www.teamliquid.net/tournaments/*
// @exclude       http://www.teamliquid.net/vods/*
// @exclude       http://www.teamliquid.net/mirror/ad*
// @run-at        document-end
// ==/UserScript==

/*  Notes:        This should be fully compatible with Firefox (Greasemonkey)/Chrome/Opera.
*                 Opera users should replace the .user.js extension with just a .js before putting it into the userjs directory.
*
*  Changelog:
*	 20120102:   Fixed the original script to work with the changed TL.net design
*/

// Wrap the script in an anonymous function so Opera doesn't blow up
(function() {
	function strip(html)
	{
	   var tmp = document.createElement("DIV");
	   tmp.innerHTML = html;
	   return tmp.textContent||tmp.innerText;
	}

	// Taken from http://www.drunkenfist.com/304/2008/07/16/my-new-getelementsbyclass-a-safari-31-oddity/ 
	function getElementsByClass(theClass,node) {
	    var classElements = [];
	    var i;
	    if ( node == null ) {
	    	node = document
	    }
	    if (node.getElementsByClassName) {
	    	var tempCollection = node.getElementsByClassName(theClass);
	        for (i = 0; i < tempCollection.length ; i++) {
	    		classElements.push(tempCollection[i])
	    	}
	    }
	    else {
	    	var els = node.getElementsByTagName("*");
	    	var elsLen = els.length;
	    	var pattern = new RegExp("(^|\\s)"+theClass+"(\\s|$)");
	    	for (i = 0; i < elsLen; i++) {
	    		if ( pattern.test(els[i].className) ) {
	    			classElements.push(els[i]);
	    		}
	    	}
	    }
	    return classElements;
	};
	
	function populatePR(pr) {
		/* Check if PR has been fetched first */
		if (!localStorage["pr_data"] || localStorage["pr_data"].length == 0)
			return false;
		
		var pr_data = JSON.parse(localStorage["pr_data"]);

		if (pr_data.length != 10)
			return false;

		/* Wipe out PR table */
		while (pr.innerTable.hasChildNodes()) {
			pr.innerTable.removeChild(pr.innerTable.firstChild);
		}

		var tableBody = document.createElement("tbody");
		pr.innerTable.appendChild(tableBody);

		for (var i = 0; i < 5; i++) {
			var currentRow = document.createElement("tr");
			var left = document.createElement("td");
			left.setAttribute("style", "font-size:8pt;");
			left.innerHTML = (i + 1) + ". " + pr_data[i];
	
			var right = document.createElement("td");
			right.setAttribute("style", "font-size:8pt;");
			right.innerHTML = (i + 6) + ". " + pr_data[i + 5];
	
			currentRow.appendChild(left);
			currentRow.appendChild(right);
			tableBody.appendChild(currentRow);
		}
		
		var pr_comment_link = pr.elements[1].querySelector("#nav_powerrank_link");
		pr_comment_link.innerHTML = "&nbsp;&nbsp;<a href='" + localStorage["pr_link"] + "' class='rightmenu'>"+localStorage["pr_comments"]+"</a>";
		return true;
	}
	
	function main() {
		var liquipedia = new Section("nav_wiki", 1);

		/* Add the PR back */
		var pr = new Object();
		pr.elements = new Array();
		
		var pr_link = document.createElement("a");
		pr_link.setAttribute("href", "/powerrank/");
		pr_link.setAttribute("style", "display:block; background-image: url('/mirror/layout/SidebarSprite2.png'); background-position: -1080px 0px");
		pr_link.setAttribute("class", "spr");
		pr_link.setAttribute("id", "nav_powerrank");
		pr.elements.push(pr_link);
		
		var pr_table = document.createElement("table");
		pr_table.setAttribute("class", "sidemenu");
		pr_table.innerHTML = '<tbody><tr><td class="sidemenu" style="padding-top:4px; padding-bottom:2px;padding-left:15px"><table id="nav_powerrank_innertable"></table></td></tr><tr><td class="sidemenu" style="padding-top:5px;" id="nav_powerrank_link">&nbsp;&nbsp; <a href="/powerrank/" class="rightmenu">Comments</a></td></tr><tr><td class="sidemenu" height="5"></td></tr></tbody></table>';
		pr.elements.push(pr_table);
		pr.innerTable = pr_table.querySelector("#nav_powerrank_innertable");
		
		populatePR(pr);
			
		if (+new Date > (parseInt(localStorage["pr_time"]) || 0) + 60000) { // Check every minute or if PR data not found
			var xmlhttp = new XMLHttpRequest();
			xmlhttp.open("GET", "/powerrank/",true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4) {
					// This is a terrible hack but fuck it
					var tdiv = document.createElement("div");
					tdiv.innerHTML=xmlhttp.responseText;
					var tables = getElementsByClass("pr_table", tdiv);

					// Assume the first table is the current power rank
					var pr_current = tables[0];
					var pr_comment_link = nextObject(pr_current);
					while (pr_comment_link.tagName != "A")
						pr_comment_link = nextObject(pr_comment_link);
					
					var names = getElementsByClass("pr_nametd", pr_current);
					var pr_names = new Array();
					for (var i = 0; i < names.length; i++) {
						pr_names.push(names[i].getElementsByTagName("b")[0].innerHTML);
					}
					localStorage["pr_time"] = +new Date;
					localStorage["pr_link"] = pr_comment_link.getAttribute("href");
					localStorage["pr_comments"] = pr_comment_link.innerHTML;
					localStorage["pr_data"] = JSON.stringify(pr_names);
					populatePR(pr);
				}
			}
			xmlhttp.send(null)
		}
		else {
		}

		/* Readd the power rank section */
		prepend_section(pr, liquipedia);
	}

	function Section(id, count) {
		this.elements = new Array();

		var link = document.getElementById(id);
		this.elements.push(link);
		for (var x = 0; x < count; x++) {
			this.elements.push(nextObject(link));
		}
	}

	var remove_section = function(section) {
		for (var x = 0; x < section.elements.length; x++) {
			var node = section.elements[x];
			node.parentNode.removeChild(node);
		}
	}

	var prepend_section = function(section, location) {
		var loc = location.elements[0];
		for (var x = 0; x < section.elements.length; x++) {
			var node = section.elements[x];
			loc.parentNode.insertBefore(node, loc);
		}
	}

	var move_section = function(from, to) {
		remove_section(from);
		prepend_section(from, to);
	}

/* Adapted from http://v3.thewatchmakerproject.com/journal/329/ */
var nextObject = function(el, count) {	
	count = count || 1;
	var n = el;
	for (var i=0; i<count; i++) {
		do n = n.nextSibling;
		while (n && n.nodeType != 1);
	}
	return n;
}

var previousObject = function(el, count) {	
	count = count || 1;
	var p = el;
	for (var i=0; i<count; i++) {
		do p = p.previousSibling;
		while (p && p.nodeType != 1);
	}
	return p;
}

if (window.opera) {
	if (document.readyState==="loading")  {
		if (window.addEventListener)
		window.addEventListener("DOMContentLoaded", main, false);
		else if (window.attachEvent)
		window.attachEvent("onload", main);
	}
	else if (document.readyState==="complete") {
		main();
	}
	else {
		if (window.addEventListener)
		window.addEventListener("load", main, false);
		else if (window.attachEvent)
		window.attachEvent("onload", main);
	}
}
else {
	main();
}
})();
